<?php

class Core_Request_Application_Http extends Soul_Request_Application_Http {

	public function __construct(){
		parent::__construct();
	}
    
    protected function beforeInitialize() {
        $this->matchWebsite();
        $this->initializeComponent();
        parent::beforeInitialize();
    }
    
    protected static function matchWebsite(){
        $currentWebsite = NULL;
        $uri = $_SERVER['REQUEST_URI'];
        if(substr($uri, -1) == '/'){
            $uri .= '/';
        }
        $websites = App::getModel('system/website')
                        ->getQuery()
                        ->condition('domain_name', $_SERVER['SERVER_NAME'])
                        ->fetchCollection();
        foreach($websites as $website){
            if($website->getDomainName() == $_SERVER['HTTP_HOST']){
                $enterUrl = $website->getEnterUrl();
                if(!empty($enterUrl)){
                    $len = strlen($website->getEnterUrl());
                    if(substr($uri, 0, $len + 2) == '/'.$website->getEnterUrl().'/'){
                        $currentWebsite = $website;
                        break;
                    }
                }else{
                    $currentWebsite = $website;
                }
            }
        }
        
        if(is_null($currentWebsite)){
            foreach($websites as $website){
                if($website->getIsDefault()){
                    $currentWebsite = $website;
                    break;
                }
            }        
        }
        
        $pos = strpos($currentWebsite->getDomainName(), '.');
        $subDomain = substr($currentWebsite->getDomainName(), 0, $pos);
        $mainDomain = substr($currentWebsite->getDomainName(), $pos + 1);
        $baseUrl = $currentWebsite->getIsDefault()? '': $currentWebsite->getEnterUrl().'/';
        Soul_Config::addDomain('backend', $mainDomain, $baseUrl.'backend', $subDomain, FALSE);
        Soul_Config::addDomain('member', $mainDomain, $baseUrl.'member', $subDomain, FALSE);
        Soul_Config::addDomain('frontend', $mainDomain, $baseUrl.'/', $subDomain, TRUE);
        ini_set('session.cookie_domain', $mainDomain);
        Soul_Request_Context::getInstance()->setData('running_website', $currentWebsite);
    }
    
    protected static function initializeComponent(){
		$dirs = scandir(DP_CODE.'Core'.DS.'Component');
        //initialize config
		foreach($dirs as $dir){
			if($dir != '.' && $dir != '..' && is_dir(DP_CODE.'Core'.DS.'Component'.DS.$dir)){
                if(file_exists(DP_CODE.'Core'.DS.'Component'.DS.$dir.DS.'config.yml')){
                    $config = Soul_Util_Yaml::parseFile(DP_CODE.'Core'.DS.'Component'.DS.$dir.DS.'config.yml');
                    if(isset($config['request']) && isset($config['request']['methodClasses'])){
                        foreach($config['request']['methodClasses'] as $className){
                            Soul_Request_Context_Helper::registerClass(Soul_Loader::loadClass($className));
                        }
                    }
                    if(isset($config['template']) && isset($config['template']['methodClasses'])){
                        foreach($config['template']['methodClasses'] as $className){
                            Soul_Template_Context_Helper::registerClass(Soul_Loader::loadClass($className));
                        }                        
                    }
                    if(isset($config['event'])){
                        foreach($config['event'] as $eventSetting){
                            Soul_Event_Manager::registerListener($eventSetting['event'],
                                    array(Soul_Loader::loadClass($eventSetting['class']), $eventSetting['method']));
                        }                        
                    }
                }
			}
		}       
    }    

	protected function afterInitialize() {
		$GLOBALS[RC]->setData('db', Soul_Db_Factory::getDriver())
					->setData('query', Soul_Db_Factory::createQuery())
					->setData('language', Soul_Language_Factory::getTranslator())
					->setData('culture', Soul_Language_Factory::getCulture())
					->setData('location', Soul_Loader::loadInstance('Soul_Collection_List'));
		parent::afterInitialize();
	}

	protected function afterRoute(){
		$dn = $GLOBALS[RC]->getRouter()->getDomain()->getName();
		$GLOBALS[RC]->setData('template_theme', 'default');
		$GLOBALS[RC]->setData('template_directories', array(DP_DESIGN.$dn.DS.'default'.DS));
		Soul_Template_Context::getInstance()->setData('template_theme', 'default');
		Soul_Config::addTemplateDirectory(DP_DESIGN.$dn.DS.'default'.DS.'html');
		parent::afterRoute();
	}

	protected function finish() {

	}

	public function run() {
		$this->initialize();
		$this->sessionStart();
		$this->route();
		$this->filter();
		$this->authentication();
		$this->handle();
		$this->output();
		$this->finish();
	}
}